package br.ufrgs.meetapp.activities;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import br.ufrgs.meetapp.dialogs.PopupLogin;
import br.ufrgs.meetapp.dialogs.PopupMessage;
import br.ufrgs.meetapp.enums.Role;
import br.ufrgs.meetapp.utils.UserPreferencesPersistence;

public class SettingsActivity extends Activity implements OnClickListener, OnItemSelectedListener, OnCheckedChangeListener {
	
	private ToggleButton trackerToggle;
	private ToggleButton trackOthersToggle;
	private Button saveButton;
	private PopupLogin popup;

	private CheckBox movementDetection;
	
	private Spinner timeIntervalSpinner;
	private Spinner distanceIntervalSpinner;
	private Spinner courseRangeSpinner;
	private Spinner sendingIntervalSpinner;
	private Spinner acquireTimeoutSpinner;
	private Spinner motionSpeedThresholdSpinner;
	private Spinner motionStopThresholdSpinner;	
	private Spinner preSetsSpinner;
	
	private Context context;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.settings_activity);
		

		if(!LoginActivity.loggedUser.getRoleList().contains(Role.ADMIN)){
			Toast.makeText(this, R.string.settings_user_is_not_admin, Toast.LENGTH_LONG).show();
			finish();
		}
		
		context = this;
		
		setTitleBar();
		initializeViews();
		populateViews();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	/**
	 * Initialize the view values
	 */
	private void initializeViews() {
		saveButton = (Button) findViewById(R.id.settingsButtonSave);
		saveButton.setOnClickListener(this);


		trackerToggle = (ToggleButton) findViewById(R.id.settingsToggleTracker);

		trackOthersToggle = (ToggleButton) findViewById(R.id.settingsToggleTrackOthers);
		
		
		preSetsSpinner = (Spinner) findViewById(R.id.settings_preset_spinner);
		preSetsSpinner.setOnItemSelectedListener(this);	
		preSetsSpinner.setSelection(UserPreferencesPersistence.getPresetSelected(context));
		
		movementDetection = (CheckBox) findViewById(R.id.settingsMovementDetectionCheckbox);
		movementDetection.setOnCheckedChangeListener(this);
		
		timeIntervalSpinner = (Spinner) findViewById(R.id.settings_time_interval_spinner);
		distanceIntervalSpinner = (Spinner) findViewById(R.id.settings_distance_interval_spinner);
		courseRangeSpinner = (Spinner) findViewById(R.id.settings_course_range_spinner);
		sendingIntervalSpinner = (Spinner) findViewById(R.id.settings_sending_interval_spinner);
		acquireTimeoutSpinner = (Spinner) findViewById(R.id.settings_acquire_timeout_spinner);
		motionSpeedThresholdSpinner = (Spinner) findViewById(R.id.settings_motion_speed_threshold_spinner);
		motionStopThresholdSpinner = (Spinner) findViewById(R.id.settings_motion_stop_threshold_spinner);
	
	}
	
	/**
	 * Called to refresh the values seted on the views
	 */
	private void populateViews(){
		
//		trackerToggle.setChecked(!((Boolean)settings.getValue(SettingsComponent.TRACKER_OFF)));
//		
//		trackOthersToggle.setChecked((Boolean)settings.getValue(SettingsComponent.TRACKER_OTHERS_ON)); 
//		
//		int timeIntervalIndex = timeIntervalArray.indexOf((Integer)settings.getValue(SettingsComponent.TIME_INTERVAL));
//		timeIntervalSpinner.setSelection(timeIntervalIndex);
//		
//		int distanceIntervalIndex = distanceIntervalArray.indexOf((Integer)settings.getValue(SettingsComponent.DISTANCE_INTERVAL));
//		distanceIntervalSpinner.setSelection(distanceIntervalIndex);
//		
//		int courseRangeIndex = courseRangeArray.indexOf((Integer)settings.getValue(SettingsComponent.COURSE_RANGE));
//		courseRangeSpinner.setSelection(courseRangeIndex);
//		
//		int sendingIntervalIndex = timeIntervalArray.indexOf((Integer)settings.getValue(SettingsComponent.SENDING_INTERVAL));
//		sendingIntervalSpinner.setSelection(sendingIntervalIndex);
//		
//		int acquireTimeoutIndex = acquireTimeoutArray.indexOf((Integer)settings.getValue(SettingsComponent.ACQUIRE_TIMEOUT));
//		acquireTimeoutSpinner.setSelection(acquireTimeoutIndex);
//		
//		int motionSpeedThresholdIndex = motionSpeedThresholdArray.indexOf((Integer)settings.getValue(SettingsComponent.MOTION_SPEED_THRESHOLD));
//		
//		int motionStopThresholdIndex = motionStopThresholdArray.indexOf((Integer)settings.getValue(SettingsComponent.MOTION_STOP_THRESHOLD));
//		
//		if(motionSpeedThresholdIndex == 0 && motionStopThresholdIndex == 0){
//			movementDetection.setChecked(false);
//			motionSpeedThresholdSpinner.setEnabled(false);
//			motionStopThresholdSpinner.setEnabled(false);
//			motionSpeedThresholdSpinner.setSelection(0);
//			motionStopThresholdSpinner.setSelection(0);
//		} else {
//			movementDetection.setChecked(true);
//			motionSpeedThresholdSpinner.setEnabled(true);
//			motionStopThresholdSpinner.setEnabled(true);
//			motionSpeedThresholdSpinner.setSelection(motionSpeedThresholdIndex);
//			motionStopThresholdSpinner.setSelection(motionStopThresholdIndex);
//		}

	}
	
	/**
	 * Called to disable fields when a pre-set is setted
	 */
	private void disableFields(){

		movementDetection.setEnabled(false);
		timeIntervalSpinner.setEnabled(false);
		distanceIntervalSpinner.setEnabled(false);
		courseRangeSpinner.setEnabled(false);
		sendingIntervalSpinner.setEnabled(false);
		acquireTimeoutSpinner.setEnabled(false);
		motionSpeedThresholdSpinner.setEnabled(false);
		motionStopThresholdSpinner.setEnabled(false);
	
	}
	
	/**
	 * Called to enable fields when a pre-set is setted
	 */
	private void enableFields(){
		movementDetection.setEnabled(true);
		timeIntervalSpinner.setEnabled(true);
		distanceIntervalSpinner.setEnabled(true);
		courseRangeSpinner.setEnabled(true);
		sendingIntervalSpinner.setEnabled(true);
		acquireTimeoutSpinner.setEnabled(true);
		motionSpeedThresholdSpinner.setEnabled(true);
		motionStopThresholdSpinner.setEnabled(true);
	}

	/***
	 * Sets the top bar
	 */
	private void setTitleBar() {
		TextView titleBarTitle;
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.title_bar);
		titleBarTitle = (TextView) findViewById(R.id.title_bar_text_title);
		titleBarTitle.setText(R.string.settings_title);
	}

	/**
	 * Create the hard-button menu
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu_account_about, menu);
		return true;
	}

	/**
	 * Actions to the hard-button menu
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = null;
		switch (item.getItemId()) {
//		case R.id.menuAccount:
//			intent = new Intent(this, AccountActivity.class);
//			break;
		case R.id.menuAbout:
			intent = new Intent(getApplicationContext(), AboutActivity.class);
			break;
		}
		
		if(intent!=null){
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		}

		return false;
	}
	
	@Override
	public void onItemSelected(AdapterView<?> spinner, View view, int position,
			long arg3) {
		switch (spinner.getId()) {
		case R.id.settings_preset_spinner:
			if(position == 3){
				enableFields();
			} else {
//				settings.setPreset(position);
				populateViews();
				disableFields();
			}
			break;

		default:
			break;
		}
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub	
	}
	
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if(buttonView.getId() == R.id.settingsMovementDetectionCheckbox){
			if(isChecked){
				motionSpeedThresholdSpinner.setEnabled(true);
				motionStopThresholdSpinner.setEnabled(true);
//				motionSpeedThresholdSpinner.setSelection(DEFAULT_SPEED_THRESHOLD_SELECTION);
//				motionStopThresholdSpinner.setSelection(DEFAULT_STOP_THRESHOLD_SELECTION);
				
			}else{
				motionSpeedThresholdSpinner.setEnabled(false);
				motionStopThresholdSpinner.setEnabled(false);
				motionSpeedThresholdSpinner.setSelection(0);
				motionStopThresholdSpinner.setSelection(0);
			}
		}
		
	}
	
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.settingsButtonSave:
			try {

//				refreshUserChanges();
//				
//				if(settings.hasChanged()){
//					// ASK FOR LOGIN CONFIRMATION
//					verifyLogin();
//				} else{
//					Toast.makeText(this, getString(R.string.no_changes), Toast.LENGTH_LONG).show();
//					
//					this.finish();
//				}

			} catch (Exception exception) {
				System.out
						.println("Error in SettingsActivity.onClick - saving the preferences");
				if (exception.getMessage() != null)
					System.out.println(exception.getMessage());
				exception.printStackTrace();
			}
			break;

		default:
			break;
		}
	}
	
//	@Override
//	public void onBackPressed() {
		//Check for user changes
//		refreshUserChanges();
//		if(settings.hasChanged()){
//		   
//		// listener to cancel button
//			android.content.DialogInterface.OnClickListener noListener = new DialogInterface.OnClickListener() {
//				public void onClick(DialogInterface dialog, int whichButton) {
//					dialog.cancel();
//					SettingsActivity.this.finish();
//				}
//			};
//			
//			// listener to ok button
//			android.content.DialogInterface.OnClickListener yesListener = new DialogInterface.OnClickListener() {
//				public void onClick(DialogInterface dialog, int whichButton) {
//					verifyLogin();
//				}
//			};
//		   PopupMessage errorPopup = new PopupMessage(this,
//					getString(R.string.unsaved_changes), getString(R.string.unsaved_changes_message),
//					getString(R.string.yes_button),getString(R.string.no_button), yesListener,noListener);
//			errorPopup.display();
//	   } else{
//		   SettingsActivity.this.finish();
//	   }
//	}

	public static boolean verifyLogin(String username, String password) {
		if (username.toLowerCase().equals(LoginActivity.loggedUser.getUsername().toLowerCase())
				&& password.toLowerCase().equals(LoginActivity.loggedUser.getPassword().toLowerCase())) {
			return true;
		} else {
			return false;
		}
	}
	
	
	private void verifyLogin(){
		// listener to ok button
		android.content.DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				if (SettingsActivity.verifyLogin(popup
						.getDialogUsernameTextView().getText()
						.toString(), popup.getDialogPasswordTextView()
						.getText().toString())) {

//					saveSettings();

				} else {
					// TODO: show login fail message
					PopupMessage errorPopup = new PopupMessage(
							SettingsActivity.this,
							getString(R.string.login_error), getString(R.string.webservice_login_input_error),
							getString(R.string.ok_button), null);
					errorPopup.display();
				}
			}
		};

		// listener to cancel button
		android.content.DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
			}
		};

		popup = new PopupLogin(this, getString(R.string.confirm_login), null, getString(R.string.ok_button),
				getString(R.string.cancel_button), okListener, cancelListener);
		popup.display();
	}

	

}
